package edu.gyc.test;

import java.util.concurrent.atomic.AtomicStampedReference;

public class MoneyAbaSolution {
    static AtomicStampedReference<Integer> money = new AtomicStampedReference<>(10, 0);

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            int versionStamp=money.getStamp();
            new Thread(()->{
                while (true) {
                    while (true) {
                        Integer m=money.getReference();
                        if(m<20){
                            if (money.compareAndSet(m, m + 20,versionStamp,versionStamp+1)) {
                                System.out.println("余额小于20，充值成功，余额：" + money.getReference() + "元");
                                break;
                            }
                        }else {
                            break;
                        }
                    }
                }
            },"后台线程"+i).start();
        }

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                while (true) {
                    Integer m=money.getReference();
                    int versionStamp=money.getStamp();
                    if(m>10){
                        System.out.println("余额大于10元");
                        if (money.compareAndSet(m, m - 10,versionStamp,versionStamp+1)) {
                            System.out.println("成功消费10元，余额："+money.getReference());
                            break;
                        }
                    }else {
                        System.out.println("余额不足，不能消费10元");
                        break;
                    }


                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
